package com.example.base.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.base.ILifecycler;
import com.example.base.utils.ReflectUtils;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @ autor huangxing7
 * @ date 2018/9/4
 * @ company 杭州海康威视数字技术股份有限公司
 * @ describe
 */
public abstract class BaseFragment2<P extends IBasePresenter2> extends Fragment
        implements ILifecycler<P> {

    protected P mPresenter;

    protected Context mContext;

    /**
     * view是否初始化
     */
    private boolean isInitView = false;

    /**
     * 第一次调用
     */
    private boolean firstOne = true;

    private Unbinder unbinder;
    protected StatusViewHelper2 mStatusViewHelper;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mStatusViewHelper = new StatusViewHelper2(getActivity(),initLayout());

        View contentView = mStatusViewHelper.getContentLayout();

        unbinder = ButterKnife.bind(this, contentView);

        isInitView = true;
        return contentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initPresenter();
        lazy(getUserVisibleHint());
    }

    private void lazy(boolean visibleOrHidden) {
        if (isInitView && visibleOrHidden) {
            if (firstOne) {
                firstOne = false;
                todo();
            } else {
                onFragmentChange();
            }
        }
    }

    /**
     * 初始化presenter
     */
    private void initPresenter() {
        mPresenter = (P) ReflectUtils.getGenericInstance(this.getClass());
        if (mPresenter != null) {
            mPresenter.onstart();
        }
    }

    /**
     * 每次fragment改变调用的方法
     */
    protected void onFragmentChange() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mPresenter != null) {
            mPresenter.onDestory();
            mPresenter = null;
        }

        if (unbinder != null) {
            unbinder.unbind();
            unbinder = null;
        }

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        lazy(isVisibleToUser);
    }
}
